// pages/screens/result/type/type.js
const screentemplateservice = require("../../../../apiservice/screen/screentemplateservice.js");
const screenresultservice = require("../../../../apiservice/screen/screenresultservice.js");
const leadservice = require("../../../../apiservice/lead/leadservice.js");
const app = getApp();
const regeneratorRuntime = app.globalData.regeneratorRuntime;
const jsonData = require("../../jsondata.js");
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		stage:'',//学校等级（中学、幼儿园....等等）
		schoolId:'', //用来查看校园筛查报告
		templateid: null,
		scid: '',
		customerid: '',
		leadid: '',
		leadName: '',
		scinfo: {},
		screentemplate: null,
		showncategoryid: '',
		addOrMod: 'add',
		finishCategoryArray: [],
		//选项集
		firstDiagnosis: jsonData.firstDiagnosis,
		firstDiagnosisIndex: 0,
		whichEyeIndex: -1,
		adviseshow: false,
		actions: [{
				name: '初期白内障随访'
			},
			{
				name: '注意用眼,如有不适请到院就诊'
			},
			{
				name: '到院复查'
			},
			{
				name: '住院手术'
			},
		],
		//双 左 右
		bothOrLeftOrRight: ['SC0000000020', 'SC0000000002', 'SC0000000001'],
		/**诊断及建议 */
		//第一诊断
		firstDiagnosiResult: {
			new_scid: null,
			new_categoryid: 'LB0012',
			new_itemid: 'XM0054',
			new_contentid: 'NR0153',
			new_result: '',
			new_doctorid: null,
			ownerid: null
		},
		//总结建议
		summary: {
			new_scid: null,
			new_categoryid: 'LB0012',
			new_itemid: 'XM0046',
			new_contentid: 'NR0142',
			new_result: '',
			new_doctorid: null,
			ownerid: null
		},
		//双眼、左、右
		whichEye: {
			new_scid: null,
			new_categoryid: 'LB0012',
			new_itemid: 'XM0054',
			new_contentid: 'NR0154',
			new_result: 'SC0000000020',
			new_doctorid: null,
			ownerid: null
		},
		/**初步诊断**/
		preliminaryDiagnosis: {
			new_scid: null,
			new_categoryid: 'LB0012',
			new_itemid: 'XM0056',
			new_contentid: 'NR0158',
			new_result: '',
			new_doctorid: null,
			ownerid: null
		},
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function(options) {
		console.log(options);
		var options = options;
		if (options) {
			this.setData({
				leadName: options.leadname,
				customerid: options.sccustid,
				scid: options.scid,
				categoryid: options.categoryid,
				leadid: options.leadid
			})
			if (options.templateid) {
				this.setData({
					templateid: options.templateid
				})
				//获取筛查类别
				this.getCategors(options.templateid);
			}
			if (options.schoolId) {
                this.setData({
					schoolId: options.schoolId
				})
			}
			if(options.stage){
				this.setData({
					stage: options.stage
				})
			}
			//获取总结建议信息
			this.getSummaryResults(options.scid, options.sccustid, 'LB0012');
		}
	},
	onShow: function() {
		this.getSelectedByScreenIdAndCustomerId();
		var that = this;
		const eventChannel = this.getOpenerEventChannel();
		eventChannel.on('acceptDataFromOpenerPage', function(data) {
			console.log('scinfo', data.data);
			that.setData({
				scinfo: data.data
			})
		})
	},
	/**
	 * 提交筛查结果
	 */
	summarySubmit: function() {
		var summary = this.data.summary;
		if (summary.new_result == '') {
			wx.showToast({
				title: '请填写描述',
				icon: 'none'
			})
			return false;
		}
		var createResult = this.getSummary();
		this.createScreenResults(createResult);
	},
	preliminaryDiagnosisSubmit: function() {
		var preliminaryDiagnosis = this.data.preliminaryDiagnosis;
		if (preliminaryDiagnosis.new_result == '') {
			wx.showToast({
				title: '请填写描述',
				icon: 'none'
			})
			return false;
		}
		var createResult = [];
		preliminaryDiagnosis.new_scid = this.data.scid;
		preliminaryDiagnosis.new_customerid = this.data.customerid;
		createResult.push(preliminaryDiagnosis);
		var screenResultRequest = {}
		screenResultRequest.screenResults = createResult;
		screenResultRequest.screenCustomer = {
			new_customerid:this.data.customerid,
			new_scid:this.data.scid
		}
		this.createScreenResultsSchool(screenResultRequest);
	},
	summaryUpdate: function() {
		var summary = this.data.summary;
		if (summary.new_result == '') {
			wx.showToast({
				title: '请填写描述',
				icon: 'none'
			})
			return false;
		}
		var updateResult = this.getSummary();
		this.updateScreenResults(updateResult);
	},
	preliminaryDiagnosisUpdate: function() {
		var preliminaryDiagnosis = this.data.preliminaryDiagnosis;
		if (preliminaryDiagnosis.new_result == '') {
			wx.showToast({
				title: '请填写描述',
				icon: 'none'
			})
			return false;
		}
		var updateResult = [];
		preliminaryDiagnosis.new_scid = this.data.scid;
		preliminaryDiagnosis.new_customerid = this.data.customerid;
		updateResult.push(preliminaryDiagnosis);
		this.updateScreenResults(updateResult);
	},
	//获取结果集
	getSummaryResults: async function(scid, customerid, categoryid) {
		wx.showLoading({
			title: '加载中...',
			mask: true,
		})
		var success = await screenresultservice.GetScreenResultByCategory(scid, customerid, categoryid);
		var reusltArray = success.data
		if (reusltArray.length == 0) {
			wx.hideLoading();
			return;
		}
		this.setData({
			addOrMod: 'mod'
		})
		for (let index in reusltArray) {
			var element = reusltArray[index];
			if (element.new_contentid === 'NR0153') {
				var itemIndex = this.data.firstDiagnosis.findIndex(
					function(item, index) {
						return item.id == element.new_result;
					}
				)
				console.log(itemIndex, );
				this.setData({
					firstDiagnosiResult: element,
					firstDiagnosisIndex: itemIndex,
				})
			} else if (element.new_contentid === 'NR0142') {
				this.setData({
					summary: element
				})
			} else if (element.new_contentid === 'NR0154') {
				this.setData({
					whichEye: element
				})
			} else if (element.new_contentid === 'NR0158') {
				this.setData({
					preliminaryDiagnosis: element
				})
			}
		}
		wx.hideLoading();
	},
	/**总结建议选项集、文本赋值 */
	firstDiagnosisChange: function(e) {
		if (e.detail.value == 0) {
			this.setData({
				whichEyeIndex: 0
			})
		}
		this.setData({
			firstDiagnosisIndex: e.detail.value
		})
	},
	onWhichEyeChange: function(e) {
		this.setData({
			whichEyeIndex: e.detail.index
		})
	},
	onSummaryChange: function(e) {
		var result = 'summary.new_result';
		this.setData({
			[result]: e.detail
		})
	},
	//打开建议
	onClickIcon: function(e) {
		this.setData({
			adviseshow: true
		})
	},
	//关闭建议
	adviseonClose: function() {
		this.setData({
			adviseshow: false
		})
	},
	//选择建议
	adviseonSelect: function(e) {
		//console.log(e);
		this.setData({
			adviseshow: false,
			['summary.new_result']: e.detail.name
		})
	},
	onPreliminaryDiagnosisChange: function(e) {
		var result = 'preliminaryDiagnosis.new_result';
		this.setData({
			[result]: e.detail
		})
	},
	//查看报告
	enterDetail: async function(e) {
		
		let scid = this.data.scid;
		//let lead = this.data.scinfo;
    var lead = {};
    var data = await leadservice.QueryLeadInfoById(this.data.leadid);
    lead.leadid = data.data.leadId;
    lead.customername = data.data.lastName;
    lead.age = data.data.new_age;
    lead.sex = data.data.new_gender;
    lead.iphoneno1 = data.data.new_phone;
    lead.sfz = data.data.new_citizenid;
    lead.createdon = data.data.modifiedOn;
		//debugger;
		let schoolId = this.data.schoolId;
		let tourl =`/pages/print/letter/letter?scid=${scid}`;
		if(schoolId)
		{
			tourl+=`&schoolId=${schoolId}`;
		}
	
		wx.navigateTo({
			url: tourl,
			events: {
				// 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
				acceptDataFromOpenedPage: function(data) {
					debugger;
					console.log(data)
				},
				someEvent: function(data) {
					console.log(data)
				}
			},
			success: function(res) {
				// 通过eventChannel向被打开页面传送数据
				res.eventChannel.emit('acceptDataFromOpenerPage', {
					data: lead
				})
			}
		})
	},
	//筛查类型的页面跳转
	showCategory: function(e) {
		var leadName = this.data.leadName;
		var customerid = this.data.customerid;
		var scid = this.data.scid;
		var leadid = this.data.leadid;
		var stage = this.data.stage;
		var showncategoryid = e.currentTarget.dataset.id
		var root = '../../../resultype/';
		var pagename = 'eyesight/eyesight';
		if (showncategoryid == 'LB0007') {
			pagename = 'eyesight/eyesight';
		} else if (showncategoryid == 'LB0002') {
			pagename = 'corneal/corneal';
		} else if (showncategoryid == 'LB0006') {
			pagename = 'systemicdiseases/systemicdiseases';
		} else if (showncategoryid == 'LB0001') {
			pagename = 'cataract/cataract';
		} else if (showncategoryid == 'LB0005') {
			pagename = 'refractiveexamination/refractiveexamination';
		} else if (showncategoryid == 'LB0008') {
			pagename = 'diabeticretinopath/diabeticretinopath';
		} else if (showncategoryid == 'LB0013') {
			pagename = 'dioptertest/dioptertest';
		} else if (showncategoryid == 'LB0010') {
			pagename = 'eyelid/eyelid';
		} else if (showncategoryid == 'LB0004') {
			pagename = 'glaucoma/glaucoma';
		} else if (showncategoryid == 'LB0003') {
			pagename = 'lacrimalduct/lacrimalduct';
		} else if (showncategoryid == 'LB0009') {
			pagename = 'ophthalmicmuscles/ophthalmicmuscles';
		}
		var url = root + pagename +
			`?leadname=${leadName}&sccustid=${customerid}&scid=${scid}&categoryid=${showncategoryid}&leadid=${leadid}&stage=${stage}`
    let schoolId = this.data.schoolId;
    if(schoolId)
      url += `&schoolId=${schoolId}`;
		console.log(url);
		wx.navigateTo({
			url: url,
		});

	},
	/**后台数据获取、逻辑处理 */
	//根据模板id获取类型列表
	getCategors(templateid) {
		var that = this;
		screentemplateservice.GetCategorIdByTmeplateId(templateid).then(function(success) {
			console.log(success.data);
			if (success && success.data) {
				that.setData({
					screentemplate: success.data
				})
			}

		}).catch(function(ex) {
			console.log(ex);
		})
	},
	//获取已完成的类别id列表
	getSelectedByScreenIdAndCustomerId: function() {
		var that = this;
		screenresultservice.GetSelectedByScreenIdAndCustomerId(this.data.scid, this.data.customerid).then(function(success) {
			that.setData({
				finishCategoryArray: success.data
			});
		}).catch(function(ex) {
			console.log(ex);
		})
	},
	//创建结果列表
	createScreenResults: function(resultList) {
		var that = this;
		wx.showLoading({
			title: '提交中...',
			mask: true
		})
		screenresultservice.CreateScreenResults(resultList).then(function(res) {
			console.log(res);
			if (res.data.resultState == 1) {
				var idArray = res.data.result.split('|');
				for (var i = 0; i < idArray.length; i++) {
					resultList[i].new_sc_resultId = idArray[i];
				}
				that.setData({
					addOrMod: "mod",
					firstDiagnosiResult: resultList[0],
					whichEye: resultList[1],
					summary: resultList[2],
				});
				wx.hideLoading();
				wx.showToast({
					title: '添加成功',
					icon: 'success',
					duration: 2000
				});
			} else if (res.data.resultState == 0) {
				wx.hideLoading();
				wx.showToast({
					title: '添加失败',
					icon: 'none',
					duration: 2000
				});
			}

		}).catch(function(ex) {
			console.log(ex);
			wx.hideLoading();
			wx.showToast({
				title: '添加失败',
				icon: 'none',
				duration: 2000
			});
		})
	},
	//创建结果列表(适应学校结果录入)
	createScreenResultsSchool: function(obj) {
		var that = this;
		wx.showLoading({
			title: '提交中...',
			mask: true
		})
		screenresultservice.PostBatchScreenResult(obj).then(function(res) {
			console.log(res);
			if (res.data.resultState == 1) {
				var preliminaryDiagnosis = that.data.preliminaryDiagnosis;
				preliminaryDiagnosis.new_sc_resultId = res.data.result;
				that.setData({
					addOrMod: "mod",
					preliminaryDiagnosis:preliminaryDiagnosis
				});
				wx.hideLoading();
				wx.showToast({
					title: '添加成功',
					icon: 'success',
					duration: 2000
				});
			} else if (res.data.resultState == 0) {
				wx.hideLoading();
				wx.showToast({
					title: '添加失败',
					icon: 'none',
					duration: 2000
				});
			}
	
		}).catch(function(ex) {
			console.log(ex);
			wx.hideLoading();
			wx.showToast({
				title: '添加失败',
				icon: 'none',
				duration: 2000
			});
		})
	},
	//更新结果集
	updateScreenResults: function(resultList) {
		wx.showLoading({
			title: '提交中...',
			mask: true
		})
		screenresultservice.UpdateScreenResults(resultList).then(function(res) {
			console.log(res);
			wx.hideLoading();
			if (res.data.resultState == 1) {
				wx.showToast({
					title: '修改成功',
					icon: 'success',
					duration: 2000
				});
			} else if (res.data.resultState == 0) {
				wx.showToast({
					title: '修改失败',
					icon: 'none',
					duration: 2000
				});
			}

		}).catch(function(ex) {
			console.log(ex);
			wx.hideLoading();
			wx.showToast({
				title: '添加失败',
				icon: 'none',
				duration: 2000
			});
		})
	},
	//获取潜客信息
	getLeadInfo: async function() {
		var leadid = this.data.customerid;
		var result = await leadservice.QueryLeadInfoById(leadid);
		console.log(result);
		return result.data;
	},
	/**create数组赋值 */
	getSummary: function() {
		var createResult = [];
		var scid = this.data.scid;
		var customerid = this.data.customerid;

		var firstDiagnosiResult = this.data.firstDiagnosiResult;
		var whichEye = this.data.whichEye;
		var summary = this.data.summary;
		//第一诊断
		var firstDiagnosisIndex = this.data.firstDiagnosisIndex;
		var firstDiagnosis = this.data.firstDiagnosis;
		firstDiagnosiResult.new_result = firstDiagnosis[firstDiagnosisIndex].id;
		//双、右、左
		var whichEyeIndex = this.data.whichEyeIndex;
		var bothOrLeftOrRight = this.data.bothOrLeftOrRight;
		if (whichEyeIndex > -1) {
			whichEye.new_result = bothOrLeftOrRight[whichEyeIndex];
		}

		createResult.push(firstDiagnosiResult);
		createResult.push(whichEye);
		createResult.push(summary);

		//给各结果的筛查id/联系人id赋值
		createResult.forEach(element => {
			element.new_scid = scid;
			element.new_customerid = customerid;
		});
		return createResult;
	}
})
